import appConfig from '@/config/config'
import alert from './util.alert.js';
import login from './util.login.js'

var EngineV2={};
var WEB_PATH = 'channel';//WEB虚拟路径
var SYSTEM_LOGIN_PAGE_URL = 'null';//登录URL
// var JSON_REQUEST = 'http://120.79.15.15/meeting/JsonRequest';//前后端交换URL引擎
// var url = uni.getStorageSync('loginadress');//正式
var url = appConfig.apiUrl;//调试
// var url = 'http://192.168.1.13:9999';//调试
var JSON_REQUESTV2 = url +'/channel/JsonRequest2'
var LOGIN_STAFF = null;//登录人员信息对象
var SYSTEM_RUN_MODE_ONLINE = false;//系统运行是否在线模式
var GLOBAL_PAGE_VARIABLE = null;//全局页面变量，用来页面之间变量传递

var EZ_POPUP_MESSAGE ='ez_popup_message';//前端弹出消息的参数名称
var EZ_WEBH5 =false;//是否是H5web系统，默认为电脑浏览器版本
var EZ_TRACE_PAGES =[];//页面访问留痕
var EZSSO ='ezsso';//单点登录通行证参数名
var EZSSO_REFRESH_NAME ='ezsso_refresh';
var EZSSO_REFRESH =null;//单点登录刷新通行证参数名
var SERVICE_ACTION_INTERAL =1000;//对于一些服务需要限制调用频率，在指定毫秒内不能重复调用。默认1000毫秒
var SYSTEM_NAME ='领航乐行';//系统名称
var CUSTOMER_NAME ='领航乐行';//客户名称
var LOGIN_STAFF_NAME=null;//登录人员姓名（便于前端显示）
var EXCUTING_SERVICES=[];//正在执行的服务（防止服务被多次调用）
var DESKTOP_PAGE=null;//登录后工作台链接
var CURRENT_MENU=null;//当前菜单信息
var POST_DATA_SECURITIED=false;//系统POST数据是否需要加密
var DATA_RSAED=false;//数据是否需要非对称加密
var RECORD_WORKPAGE_TRACE=false;//记录页面访问轨迹


var MULTI_USER_TOKEN = 'channel' //领航租户token

/**
*提交之前添加固定参数
*name：参数名称
*value：参数值
*/
console.log(uni.getStorageSync('EZSSO'),'ezssoezssoezssoezsso')

/**
*执行数据交换
*actionivo：前端输入对象ivo
*callback：前端提交后返回后的回调函数
*balert：是否弹出输入、输出的JSON字符串
*errorhandle：出错后制定回调函数
*/
EngineV2.action =function(actionivo, callback, balert, errorhandle)
{
	actionivo.ver =2;//版本2
	actionivo.set('multi_user_token',MULTI_USER_TOKEN)
	
	//判断客户端是否在连续调用某服务（用户多次点击）
	var multi_operate =false;
	var exist_action_service =false;

	if(actionivo.single)
	{//独占运行
		var now =(new Date()).getTime();
		for(var i=EXCUTING_SERVICES.length-1; i>=0; i--)
		{//判断执行的服务是否存在该服务并且在指定不能调用的时段内
			console.log("执行到这里",)
			if(EXCUTING_SERVICES[i].service ==actionivo.service)
			{
				if((now -EXCUTING_SERVICES[i].time) <SERVICE_ACTION_INTERAL)
				{//在限制调用的时段内
					// multi_operate =true; // 原有 
					multi_operate =false; // 修改
				}
				// exist_action_service =true; //原有
				exist_action_service =false; //修改
			}
			else if((now -EXCUTING_SERVICES[i].time) >SERVICE_ACTION_INTERAL)
			{//超过时段，则删除
				EXCUTING_SERVICES.splice(i, 1);
			}
		}
	}
	
	if(multi_operate && actionivo.single)
	{	 
		if(!SYSTEM_RUN_MODE_ONLINE)
		{//开发状态则提示，产品状态则默认丢弃，用户无感。
			// warning 警告
			uni.showModal({
				title:'提示',
				content:"请不要连续操作！" +actionivo.service +" "+actionivo.single,
				showCancel:false,
				confirmColor:'#0B5FFF',
				confirmText:'知道了',
				mask:true,
				success(res) {
					if(res.confirm) {  
						console.log('comfirm') //点击确定之后执行的代码
					}
				}
			})
		}
		return;
	}
	else
	{
		if(!exist_action_service)
		{//不存在该服务，添加
			var ec =new Object();
			ec.service =actionivo.service;
			ec.time =(new Date()).getTime();
			EXCUTING_SERVICES[EXCUTING_SERVICES.length] =ec;
		}
	}
	try
	{//设置调用时间
		if(actionivo.action_trace)
		{
			setEngineActionTime();//设置这次的操作时间
		}
	}
	catch (e)
	{
		//console.log("Engine.action:"+e);
	}

	if(actionivo.popup_waiting)
	{
		actionivo.waiting =false;
		// var guid = EZPublic.getGuid(); 
		var guid = getGuid();
		actionivo.set("guid", guid);
		//EZPublic.excuting("服务执行情况", actionivo.service, guid, actionivo.popoff_manual);
		// alert 弹框
		uni.showModal({
			title:'提示',
			content:`服务执行情况,${actionivo.service},${guid},${actionivo.popoff_manual}`,
			showCancel:false,
			confirmColor:'#0B5FFF',
			confirmText:'知道了',
			mask:true,
			success(res) {
				if(res.confirm) {  
					console.log('comfirm') //点击确定之后执行的代码
				}
			}
		})
	}
	else
	{
		if(actionivo.waiting)
		{
			console.log("执行到这里了,",actionivo.waiting)
			alert.showLoading()
			if(actionivo.waiting_div ==null)
			{
				actionivo.waiting_div ="rcc_engine_invoke";
			}
			//$("#"+actionivo.waiting_div).addClass("spinner");
		}
		else
		{
			actionivo.waiting_div ="rcc_engine_invoke";
			//$("#"+actionivo.waiting_div).addClass("spinner");
		}
	}
	if(balert && !SYSTEM_RUN_MODE_ONLINE)
	{//永远提醒
		//alert("版本2 输入：：\n"+actionivo.toJson2());
		// alert 弹框
		uni.showModal({
			title:'提示',
			content:"版本2 输入：：\n"+actionivo.toJson2(),
			showCancel:false,
			confirmColor:'#0B5FFF',
			confirmText:'知道了',
			mask:true,
			success(res) {
				if(res.confirm) {  
					console.log('comfirm') //点击确定之后执行的代码
				}
			}
		})
	}
	
	var ivojson = actionivo.toJson2();
	
	var post_url =JSON_REQUESTV2;
	if(actionivo.post_proxy !=null)
	{
		post_url =actionivo.post_proxy;
	}
	
	ivojson = processPostBefore(ivojson, actionivo);
	
	//POST数据交换处理
	var ezssostr=uni.getStorageSync('EZSSO');
	if(ezssostr!=null&&ezssostr!=""){
		ivojson=JSON.parse(ivojson)
		ivojson.ezsso= JSON.parse(ezssostr);
	}
	
	uni.request({
		method: "post",
		url: post_url,
		data: ivojson,
		sslVerify:false,
		header: {
			//'content-type': 'application/json' // 默认值
			'Content-Type': 'application/json',
			'Authorization': 'Bearer token'
		},
		//dataType: "text",
		//async:actionivo.async,
		success: function (result) 
		{
			alert.hideLoading()
			//后台返回数据处理
			// result =EZPublic.processPostAfter(result, actionivo);
			result = processPostAfter(result, actionivo);
			if(balert && !SYSTEM_RUN_MODE_ONLINE)
			{
				//alert("版本2 输出：\n"+result);
				// alert 弹框
				uni.showModal({
					title:'提示',
					content:"版本2 输入：：\n"+result,
					showCancel:false,
					confirmColor:'#0B5FFF',
					confirmText:'知道了',
					mask:true,
					success(res) {
						if(res.confirm) {  
							console.log('comfirm') //点击确定之后执行的代码
						}
					}
				})
			}

			var ovo =null;
			var msg = null;
			//console.log(actionivo,'actionivoactionivoactionivo')
			if(actionivo.ver ==2)
			{//版本2
				//console.log(eval(result),'resultresult')
				// ovo = parseJsonToOvoV2(eval(result.data));
				ovo = parseJsonToOvoV2((result.data));
				ovo.ivo = actionivo;
			}
			else
			{
				ovo =new Ovo(result, actionivo);
			}
			ovo.result =result;

			//删除正在执行的服务
			for(var ii=EXCUTING_SERVICES.length -1; ii>=0; ii--)
			{
				if(EXCUTING_SERVICES[ii].service ==actionivo.service)
				{
					EXCUTING_SERVICES.splice(ii, 1);
					break;
				}
			}
			if(ovo.getCode() <0)
			{	
				//console.log(ovo.getCode())
				//console.log(ovo.getService())
				if(ovo.getCode() =="-999997" && ovo.getService() !="loginByPassport")
				{//重新登录
					uni.navigateTo({
						url:'/sub_pages/intake/pages/login/login'
					})
				}
				else if(ovo.getCode() =="-999990" && ovo.getIvo().service !="refreshAccessToken")
				{//重新刷新
					var ivorefresh = ovo.getIvo();//设置成调用需要登录的service
					ivorefresh.remove(EZSSO);
					var failedIvoService =ivorefresh.service;
					var failedIvoServiceType =ivorefresh.service_type;
					var failedIvoJson =ivorefresh.toJson2();
					if(null==EZSSO_REFRESH||''==EZSSO_REFRESH||'undefined'==EZSSO_REFRESH||undefined==EZSSO_REFRESH){
						uni.navigateTo({
							url:'/sub_pages/intake/pages/login/login'
						})
					}else{
						ivorefresh.single =false;
						ivorefresh.setWaiting(false);
						ivorefresh.setActionTrace(false);
						
						ivorefresh.service ="refreshAccessToken";
						ivorefresh.set(EZSSO_REFRESH_NAME, EZSSO_REFRESH);
						
						EngineV2.action(ivorefresh, function(refreshOvo)
						{//刷新token后置值
							//console.log("failedIvoJson 2:"+failedIvoJson);
							var failedIvo = new Ivo();
							failedIvo.load(failedIvoJson);
							EngineV2.action(failedIvo, callback, false);
						}, false);
					}
				}
				else if(ovo.getCode() =="-999996")
				{//项目正在升级
					uni.reLaunch({
						url:'/pages/warning/comingSoon'
					})
					//window.document.location =WEB_PATH+"/include/extpages/ComingSoon.jsp";
				}
				else if(ovo.getCode() =="-999995")
				{//授权到期
					msg =ovo.getMsg();
					//alert("请保重知识产权：" +"\n" +msg);
					uni.reLaunch({
						url:'/pages/warning/license'
					})
					//window.document.location =WEB_PATH+"/platform/license/License.jsp?unvalid=1";
				}
				else if(errorhandle !=null)
				{//自定义错误处理方法
					if(errorhandle)
					{
						try
						{
							errorhandle(ovo);
						}
						catch (e)
						{
							//EZPublic.alert("提示", errorhandle);
							// alert 弹框
							uni.showModal({
								title:'提示',
								content:errorhandle,
								showCancel:false,
								confirmColor:'#0B5FFF',
								confirmText:'知道了',
								mask:true,
								success(res) {
									if(res.confirm) {  
										console.log('comfirm') //点击确定之后执行的代码
									}
								}
							})
						}
					}
				}
				else  if( ovo.result.data.msg == '非法访问，请重新登录！')
				{
					uni.navigateTo({
						url:'/sub_pages/intake/pages/login/login'
					})
					
				}
				else
				{
					msg = ovo.getMsg()+" "+ovo.getExp();
					if(!SYSTEM_RUN_MODE_ONLINE)
					{
						msg =msg +"["+actionivo.service+"]";
					}
					if(ovo.getCode() =="-999991" )
					{
						uni.navigateTo({
							url:'/sub_pages/intake/pages/login/login'
						})
						return;
					}
					uni.showToast({
						title:msg,
						icon:'none',
						mask:true,
						duration:2000,
						position:'center'
					})
				}
			}
			else
			{
				var popupMsg =ovo.get(EZ_POPUP_MESSAGE);
			
				if(popupMsg !=null && popupMsg !="")
				{
					//EZPublic.warning(popupMsg);
					// error 弹框
				
					uni.showModal({
						title:'提示',
						content:popupMsg,
						showCancel:false,
						confirmColor:'#0B5FFF',
						confirmText:'知道了',
						mask:true,
						success(res) {
							if(res.confirm) {  
								console.log('comfirm') //点击确定之后执行的代码
							}
						}
					})
				}
				//判断是否有通行证sso对象
				console.log(ovo,'476476')
				if(ovo.exist(EZSSO))
				{	
					uni.setStorageSync('EZSSO',ovo.getRow(EZSSO).toJson())
				}
				//SSO定期刷新Token参数设置
				if(ovo.exist(EZSSO_REFRESH_NAME))
				{
					EZSSO_REFRESH =ovo.getRow(EZSSO_REFRESH_NAME);
					if(ovo.exist(EZSSO_REFRESH_NAME))
					{
						uni.setStorageSync('EZSSO_REFRESH_NAME',ovo.getRow(EZSSO_REFRESH_NAME).toJson())
					}
				}
				if(callback)
				{
					//'jQuery.isFunction(callback)
					if(typeof callback === "function")
					{
						try
						{
							//如果出现弹出框，并且为自动关闭，则关闭弹出等待框
							if(actionivo.popup_waiting && !actionivo.popoff_manual)
							{
								//$("#ez-excuting-modal").modal("hide");
								callback(ovo);
							}
							else
							{
								callback(ovo);
							}
						}
						catch (e)
						{
							//EZPublic.alert("提示", e);
							// alert 弹框
							uni.showModal({
								title:'提示',
								content:e,
								showCancel:false,
								confirmColor:'#0B5FFF',
								confirmText:'知道了',
								mask:true,
								success(res) {
									if(res.confirm) {  
										console.log('comfirm') //点击确定之后执行的代码
									}
								}
							})
						}
					}
					else
					{
						//EZPublic.success(callback);
						// success 弹框
						uni.showModal({
							title:'提示',
							content:callback,
							showCancel:false,
							confirmColor:'#0B5FFF',
							confirmText:'知道了',
							mask:true,
							success(res) {
								if(res.confirm) {  
									console.log('comfirm') //点击确定之后执行的代码
								}
							}
						})
					}
				}
				if(actionivo.waiting_div !=null)
				{
					//$("#"+actionivo.waiting_div).removeClass("spinner");
				}
			}
		},
		fail: function (msg) {
			console.log(msg)
			alert.hideLoading()
			uni.showToast({
				title:'无法访问服务器，请检查网络连接。',
				icon:'none',
				mask:true,
				duration:2000,
				position:'center'
			})
			return
		},
	});
	multi_operate =false;
}
;
//通过本地数据形成调用
EngineV2.actionLocal=function(ivo, callback, result)
{
	var ovo =new Ovo(result, ivo);
	ovo.result =result;
	if(callback)
	{
		//if(jQuery.isFunction(callback))
		if(typeof callback === "function")
		{
			try
			{
				callback(ovo);
			}
			catch (e)
			{
				//alert(e);
				//EZPublic.alert("提示", callback);
				// alert 弹框
				uni.showModal({
					title:'提示',
					content:e,
					showCancel:false,
					confirmColor:'#0B5FFF',
					confirmText:'知道了',
					mask:true,
					success(res) {
						if(res.confirm) {  
							console.log('comfirm') //点击确定之后执行的代码
						}
					}
				})
			}
		}
		else
		{
			//EZPublic.success(callback);
			// alert 弹框
			uni.showModal({
				title:'提示',
				content:callback,
				showCancel:false,
				confirmColor:'#0B5FFF',
				confirmText:'知道了',
				mask:true,
				success(res) {
					if(res.confirm) {  
						console.log('comfirm') //点击确定之后执行的代码
					}
				}
			})
		}
	}
}
;

function parseJsonToOvoV2(json)
{
	var params =new OvoV2();
	for(let p in json)
	{	
		if(typeof json[p] !== 'object')
		{
			var param =new ParamV2(p, json[p], (typeof json[p])+"");
			params.push(param);
		}
		// (json[p] instanceof Array)
		
		else if(json[p] instanceof Array)    
		{
			var pp =p;
			var subparams =[];
			json[p].forEach(function(item)
			{
				if(!(item instanceof Object))    
				{
					var param =new ParamV2(null, item, typeof item);
					subparams.push(param);
				}
				else
				{
					//var subparam =parseJsonToOvoV2(item, new OvoV2());
					var subparam =parseJsonToOvoV2(item);
					subparams.push(subparam);
				}
			});
			var param =new ParamV2(pp, subparams, "dataset");
			params.push(param);
		}
		else
		{
			var pp =p;
			var subparams =parseJsonToOvoV2(json[p]);
			var param =new ParamV2(pp, subparams, "row");
			params.push(param);
		}
	}
	return params;
}

//GUID全称为全局唯一标识符，也称作 UUID，GUID是一种由算法生成的二进制长度为128位的数字标识符。GUID 的格式为“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”，其中的 x 是 0-9 或 a-f 范围内的一个32位十六进制数。GUID 的总数达到了2^128（3.4×10^38）个，所以随机生成两个相同GUID的可能性非常小，但并不为0。
function getGuid(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);  
        return v.toString(16);  
    });  
} 


//POST数据交换处理器
var security_processer =null;
//POST数据交换前处理
function processPostBefore(postdata, actionedivo){
	if(actionedivo.service=='loginAtMiniapp' ||  actionedivo.service=='getUserMobileAtMiniapp' ){
		actionedivo.remove(EZSSO)
	}
	if(actionedivo.unsecuritied)
	{//需要加密处理，默认
		console.log("使用了加密")
		//如果需要公钥加密，则先非对称加密
		// EZCommon.isDefined
		if(DATA_RSAED && isDefined(DATA_RSA_SECURITY_KEY) && DATA_RSA_SECURITY_KEY !=null
			&& DATA_RSA_SECURITY_KEY !="")
		{//加密
			postdata =SM2.doEncrypt(postdata ,DATA_RSA_SECURITY_KEY);
		}
		// EZCommon.isDefined
		if(POST_DATA_SECURITIED && isDefined(DATA_POST_SECURITY_KEY) && DATA_POST_SECURITY_KEY !=null
			&& DATA_POST_SECURITY_KEY !="")
		{
			
			if(security_processer ==null)
			{
				security_processer = new SM4Util();
				//设置POST密钥
				security_processer.secretKey=DATA_POST_SECURITY_KEY;//"LSxH5p1vs3ePYJfM";
			}
			//ECB加密
			postdata = security_processer.encryptData_ECB(postdata);
		}
	}
	return postdata;
}

//POST数据交换后处理
function processPostAfter(postdata, actionedivo){
	if(!actionedivo.unsecuritied)
	{//需要加密处理，默认
	// EZCommon.isDefined
		if(POST_DATA_SECURITIED && isDefined(DATA_POST_SECURITY_KEY) && DATA_POST_SECURITY_KEY !=null
			&& DATA_POST_SECURITY_KEY !="")
		{
			if(security_processer ==null)
			{
				security_processer = new SM4Util();
				//设置POST密钥
				security_processer.secretKey=DATA_POST_SECURITY_KEY;//"LSxH5p1vs3ePYJfM";
			}
			//ECB加密
			postdata = security_processer.decryptData_ECB(postdata);
		}
	}
	else
	{
		
		console.log(actionedivo.service +" POSTED 不需要解密处理。");
	}
	return postdata;
}

//是否已经定义参数
function isDefined(param)
{
	var defined =false;
	try
	{
		defined =!(typeof param == "undefined");
	}
	catch (e)
	{
		defined =false;
	}
	return defined;
}


export { EngineV2,EZSSO};

